package com.lry.pda.bottom.c.backend.executor;

import com.lry.pda.bottom.c.backend.FuncArgHelper;
import com.lry.pda.bottom.c.backend.code.CodeKey;
import com.lry.pda.bottom.c.backend.code.CodeNode;
import com.lry.pda.bottom.c.backend.type.Declarator;
import com.lry.pda.bottom.c.backend.type.Symbol;
import com.lry.pda.bottom.c.frontend.Grammar;

import java.util.Collections;
import java.util.List;

public class FuncDeclExecutor extends BaseExecutor{
    @Override
    public void execute(CodeNode root) {
        int production = (Integer)root.getAttr(CodeKey.PRODUCTION);
        if(production== Grammar.NEW_NAME_LP_RP_TO_FUNCT_DECL){
            copyChild(root,root.getChildren().get(0));
        }else if(production == Grammar.NEW_NAME_LP_VAR_LIST_RP_TO_FUNCT_DECL){
            Symbol symbol = (Symbol)root.getAttr(CodeKey.SYMBOL);
            //获得参数列表
            Symbol args = symbol.getArgs();
            initArgumentList(args);
        }
    }

    private void initArgumentList(Symbol args) {
        if (args == null) {
            return;
        }
        List<Object> argsList = FuncArgHelper.getSelf().getFuncArgList(true);
        Symbol eachSym = args;
        int count = 0;
        while (eachSym != null) {
            Declarator declarator = eachSym.getDeclarator(Declarator.ARRAY);
            if(null!=declarator){
                declarator.setElements((Object[]) argsList.get(count));
            }else{
                /*
                 * 将每个输入参数设置为对应值并加入符号表
                 */
                eachSym.setValue(argsList.get(count));
            }
            count++;
            eachSym = eachSym.getNext();
        }
    }

}
